﻿var map;
var isMarker = false;
var isPolyline = false;
var isLineStarted = false;
var isLineEnded = false;
var LineLocStart = null;
var divMarker = null;
var divPolyline = null;
var arrMarker = new Array();
var arrMarkerName = new Array();
var currPolyline = null;
var arrPolyline = new Array();
var arrPolylineName = new Array();
var currPicDiv = null;
var currTrailDescDiv = null;
var MarkerType = 'Trail'; //var MarkerType = ''; // Old Value
var arrMarkerDesc = new Array();
var arrWaypointsId = new Array();
var semicolon = '^^^';
var comma = ':-:';

/****************Form Elements**********************************/
var hfCenter = null;
var hfZoom = null;
var hfMarkers = null;
var hfLines = null;
var map_canvas = null;
var ViewMode = false;
var TrailsMode = false;
var hfMainImageID = null;
var hfTrails = null;
var btnDelete = null;
var hfCountry = null;

/**********Reverse Geocoding Variables**************************/
var geocoder;
var address;

/**************Animate trail markers******/
var IntervalID = null;
var prevIdx = -1;
var currIdx = 0;


/****************Google Map Functions***************************/

function initialize(p_divMarker, p_divPolyline, p_map_canvas, p_hfCenter, p_hfZoom, p_hfMarkers, p_hfLines, p_hfViewMode, p_hfMainImageID, p_hfTrails, p_btnDelete, p_hfCountry) 
{
    hfCenter = p_hfCenter;
    hfZoom = p_hfZoom;
    hfMarkers = p_hfMarkers;
    hfLines = p_hfLines;
    divMarker = p_divMarker;                //document.getElementById('divMarker');
    divPolyline = p_divPolyline;            //document.getElementById('divPolyline');
    map_canvas = p_map_canvas;
    hfMainImageID = p_hfMainImageID;
    hfTrails = p_hfTrails;
    btnDelete = p_btnDelete;
    hfCountry = p_hfCountry;

    if (hfTrails.value != "")           TrailsMode = true;
    if (p_hfViewMode.value == "1")      ViewMode = true;

    if (!GBrowserIsCompatible()) 
    {
        alert('Your browser is not compatible with the Google Maps API');
        return;
    }
    
    var center_split = hfCenter.value.split(',');
    var center = null;
    
    if (center_split.length != 2)
        center = new GLatLng(0, 0);
    else
        center = new GLatLng(center_split[0], center_split[1]);
    
    document.map = new GMap2(map_canvas);
    
    var ZoomLevel = parseInt(hfZoom.value);
    if (ViewMode)   ZoomLevel -= 1;
    
    document.map.setCenter(center, ZoomLevel);
    document.map.addControl(new GMenuMapTypeControl());
    document.map.addControl(new GLargeMapControl());
    
    if (!ViewMode) {
        geocoder = new GClientGeocoder();

        GEvent.addListener(document.map, "click", function(overlay, point) {
            Draw(point);
        });

        if (location.href.indexOf('Trail.aspx?TrailID=') > 0) {
            //   EditPolyline(this);
        }
    }
}



//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
///                 MARKERS
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////

function highlightMarker(point, idx) {
    maxDim = 150;
    UnhighlightMarker();
    if (document.map.getBounds().contains(point)) {
        var PicDesc = arrMarkerName[idx - 1];

        var hfPic = document.getElementById("hfcbm" + idx);
        var Picture = hfPic.value;
        var PictureHTML = '<img src="' + Picture + '" style="max-width:' + maxDim + 'px; max-height:' + maxDim + 'px; "/>';
        if (hfPic.value.length == 0) {
            PictureHTML = "&nbsp;";
        }


        var px1 = document.map.fromLatLngToDivPixel(point);
        var px2 = document.map.fromLatLngToDivPixel((document.map.getBounds()).getSouthWest());
        var mapHeight = parseInt(map_canvas.style.height.replace('px', ''));
        var px = new GPoint(px1.x - px2.x, px1.y - px2.y + mapHeight);
        currPicDiv = document.createElement('div');
        currPicDiv.style.position = 'absolute';
        currPicDiv.style.top = px.y + 2 + 'px';
        currPicDiv.style.left = px.x + 2 + 'px';
        currPicDiv.style.zindex = 100;
        currPicDiv.style.border = "1px solid #000000";
        var Pic = document.getElementById("hfcbm" + idx).value;
        var PicHTML = "<a href=javascript:AddPhoto(" + idx + ");>Add Photo</a>";
        if (Pic.length != 0)
            PicHTML = "<a href=javascript:EditPhoto(" + idx + ",'" + Pic + "'); >Edit Photo</a>";
        var marker = arrMarker[idx - 1];
        var icon = marker.getIcon();
        var istext = false;
        if (icon.image.toLowerCase().indexOf('text.png') > 0) {
            istext = true;
            PicHTML = "";
        }
        var editRow = '<tr><td colspan="3">' + PicHTML + ' &nbsp; <a href=javascript:showWaypointInfo(' + idx + ',' + istext + '); >Edit Text</a></td></tr>';
        if (ViewMode) {
            editRow = '';
            // Auto hide with delay for view mode
            currPicDiv.closeIt = setTimeout(UnhighlightMarker, 2000);
            currPicDiv.onmouseover = function() { clearTimeout(currPicDiv.closeIt); };
            currPicDiv.onmouseout = function() { clearTimeout(currPicDiv.closeIt); currPicDiv.closeIt = setTimeout('UnhighlightMarker()', 500); };
        }
        currPicDiv.innerHTML = '<div style="border: 2px solid #FFFFFF;display:block; background-color:#fff; "><table><tr><td>' + PictureHTML + '</td><td align="left" valign="top" width="100px" class="normal_font">' + PicDesc + '</td><td valign="top" class="normal_font"><a href="javascript:UnhighlightMarker();">X</a></td></tr>' + editRow + '</table></div>';
        map_canvas.appendChild(currPicDiv);
    }
}

function UnhighlightMarker() {
    if (currPicDiv) { map_canvas.removeChild(currPicDiv); currPicDiv = null; }
}

// if markername supplied no info window will b shown
function placeMarker(point, markerName, markerDesc) 
{
    var marker = createMarker(point);
    document.map.addOverlay(marker);
    PushMarker(marker, markerName, markerDesc);

    var idx = arrMarker.length;
    if (markerName == "" && !TrailsMode) {
        var icon = arrMarker[idx - 1].getIcon();
        var isText = false;
        if (icon.image.toLowerCase().indexOf('text.png') > 0) {
            isText = true;
        }
        showWaypointInfo(idx, isText);
    }
    if (!ViewMode) {
        GEvent.addListener(document.map, "click", function(_marker, _point, _markerPoint) {
            for (var i = 0; i < arrMarker.length; i++) {
                if (_marker == arrMarker[i]) {
                    var icon = _marker.getIcon();
                    var isText = false;
                    if (icon.image.toLowerCase().indexOf('text.png') > 0) {
                        isText = true;
                    }
                    showWaypointInfo(i + 1, isText);

                }
            }
        });
    }
    if (TrailsMode) {
        GEvent.addListener(document.map, "click", function(_marker, _point, _markerPoint) {
            var trailSplit = hfTrails.value.split(semicolon);
            if (trailSplit.length > 0) {
                for (var i = 0; i < arrMarker.length; i++) {
                    if (_marker == arrMarker[i]) {
                        var id = trailSplit[i].split(comma)[0];
                        if (id != null) {
                            document.location.href = "/UI/trail-details.aspx?TrailID=" + id;
                        }
                    }
                }
            }
        });
    }

    if (!TrailsMode) {
        GEvent.addListener(marker, "mouseover", function() {
            var p = this.getLatLng();
            highlightMarker(p, idx);
        });
    }
    else {
        GEvent.addListener(marker, "mouseover", function() {
            var p = this.getLatLng();
            highlightTrailInfo(p, idx);
        });
    }
    //      GEvent.addListener(marker, "mouseout", function() {
    //         UnhighlightMarker();
    //       //  self.mapDiv.removeChild(self.currPicDiv);
    //      });



}

function createMarker(point, color) 
{

    var f = new GIcon();
    //  f.image = "http://labs.google.com/ridefinder/images/mm_20_" + color + ".png";
    //  f.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
    f.image = "../images/Marker/" + MarkerType + ".png";
    f.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";

    if (MarkerType == "Start")
        f.iconSize = new GSize(31, 43);
    else
        f.iconSize = new GSize(22, 30);

    f.shadowSize = new GSize(32, 20);
    f.iconAnchor = new GPoint(6, 20);
    f.infoWindowAnchor = new GPoint(6, 1);
    f.infoShadowAnchor = new GPoint(13, 13);

    if (ViewMode)
        newMarker = new GMarker(point, { icon: f, draggable: false });
    else
        newMarker = new GMarker(point, { icon: f, draggable: true });

    return newMarker;
}

function EnableMarker(p_MarkerType) 
{
    //MarkerType = p_MarkerType; // My comments
    isMarker = true;
    isPolyline = false;
}

function PushMarker(Marker, MarkerName, markerDesc) {
    arrMarker.push(Marker);
    if (MarkerName == "")
        MarkerName = "Way Point Name";
    arrMarkerName.push(MarkerName);
    arrMarkerDesc.push(markerDesc);
    var markerDiv = document.createElement('div');

    var cb = document.createElement('input');
    cb.type = "checkbox";
    cb.id = "cbm" + arrMarker.length.toString();
    markerDiv.id = "div" + cb.id;
    cb.checked = true;
    cb.setAttribute("onclick", "AddRemoveMarker(this,'')");
    var label = document.createElement('label');
    label.id = "lbl" + cb.id;
    label.htmlFor = cb.id;
    label.innerHTML = MarkerName;
    var hfPic = document.createElement("input");
    hfPic.type = "hidden";
    hfPic.value = "";
    hfPic.id = "hf" + cb.id;

    markerDiv.appendChild(hfPic);
    markerDiv.appendChild(cb);
    markerDiv.appendChild(label)
    divMarker.appendChild(markerDiv);
}

function AddRemoveMarker(cb) {
    //    var btnPolyline = document.getElementById('btnPolyline');
    //    if (btnPolyline.value != "Start Track")
    //        EnablePolyline(btnPolyline);
    var idx = parseInt(cb.id.replace('cbm', ''));

    var marker = arrMarker[idx - 1];
    if (cb.checked) {
        document.map.addOverlay(marker);
        var icon = marker.getIcon();
        var isText = false;
        if (icon.image.toLowerCase().indexOf('text.png') > 0)
            isText = true;
        showWaypointInfo(idx, isText);
    }
    else {
        document.map.removeOverlay(marker);
    }
}

function SaveMarkers() {
    hfMarkers.value = "";
    for (var i = 0; i < arrMarker.length; i++) {
        var marker = arrMarker[i];
        hfMarkers.value += arrMarkerName[i] + comma;
        var latlng = marker.getLatLng();
        hfMarkers.value += latlng.lat() + comma + latlng.lng();
        var pic = document.getElementById("hfcbm" + (i + 1)).value.replace("&amp;", "&");
        var icon = marker.getIcon();
        hfMarkers.value += comma + pic + comma + icon.image.replace('../images/Marker/', '').replace('.png', '') + comma + arrMarkerDesc[i] + comma + arrWaypointsId[i] + semicolon;
    }
}

function LoadMarkers() {
    if (hfMarkers.value != "") {
        var markers = hfMarkers.value.split(semicolon);

        for (var i = 0; i < markers.length; i++) {
            var split = markers[i].split(comma);
            if (split.length == 5 || split.length == 7) {
                var point = new GLatLng(split[1], split[2]);
                if (TrailsMode) {
                    MarkerType = "Trail";
                }
                else {
                    MarkerType = split[4];
                }

                if (split.length == 5) {
                    placeMarker(point, split[0], "");
                    arrWaypointsId.push(split[5]);
                }
                else {
                    placeMarker(point, split[0], split[5]);
                    arrWaypointsId.push(split[6]);
                }
                var hfPic = document.getElementById("hfcbm" + (i + 1));
                if (split[3])
                    hfPic.value = split[3].replace("&", "&amp;");
            }
        }
    }
}

//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
///                     POLYLINE
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////

function AddToPolyline(Location, PolylineName) 
{
    var polyline = null;
    if (currPolyline == null) {

        currPolyline = polyline = new GPolyline([LineLocStart, Location], "#ff0000", 3);

        document.map.addOverlay(polyline);
        polyline.enableEditing();
        PushPolyLine(polyline, PolylineName);

        /*  EnableMarker('walk');
        placeMarker(LineLocStart, "test");
        isMarker = false;
        isLineStarted = true;*/
    }
    else 
    {
        polyline = currPolyline;
        document.map.removeOverlay(polyline);
        var vertCount = polyline.getVertexCount();
        polyline.insertVertex(vertCount, Location);
        document.map.addOverlay(polyline);
        polyline.enableEditing();
    }
}

function EndPolyline(isShowInfo) 
{
    try {
        arrPolyline[arrPolyline.length - 1].disableEditing();
        if (isShowInfo)
            showTrackInfo(arrPolyline.length);
        isLineStarted = false;
        isPolyline = false;
        LineLocStart = null;
        currPolyline = null;
    }
    catch (e) { }
}

function EnablePolyline(btn) 
{
    if (btn.value == "Start Track") {

        //(begin) place center marker on "Start Track" click
        //EnableMarker('walk');
        EnableMarker('Start');
        if (document.getElementById("ctl00_ContentPlaceHolder1_GMap1_hfStart").value != 'start') {
            document.getElementById("ctl00_ContentPlaceHolder1_GMap1_hfStart").value = "start";
        }

        // placeMarker(document.map.getCenter(), "");
        //(end) place center marker on "Start Track" click
        isMarker = false;
        isPolyline = true;
        btn.value = "End Track";
    }
    else {

        //(begin) place marker on first point
        //EnableMarker('walk');
        EnableMarker('Start');


        if (LineLocStart != null) {
            //  LineLocStart = document.getElementById("ctl00_ContentPlaceHolder1_GMap1_hfSavepoint").value;
            placeMarker(LineLocStart, "Start Point", "");
        }


        isMarker = false;
        // (end)  place marker on first point
        EndPolyline(true);
        // Show enter trail name window
        btn.style.display = 'none';
        btn.value = "Start Track";
    }
}

function PushPolyLine(Polyline, PolylineName) {
    arrPolyline.push(Polyline);
    if (PolylineName == "")
        PolylineName = "New Track Name";
    arrPolylineName.push(PolylineName);
    var PolylineDiv = document.createElement('div');
    var cb = document.createElement('input');
    cb.type = "checkbox";
    cb.id = "cbp" + arrPolyline.length.toString();
    PolylineDiv.id = "div" + cb.id;
    cb.checked = true;
    cb.setAttribute("onclick", "AddRemovePolyline(this)");
    var label = document.createElement('label');
    label.id = "lbl" + cb.id;
    label.htmlFor = cb.id;
    label.innerHTML = PolylineName + "&nbsp&nbsp;";
    /*var hyperlink = document.createElement('a');
    hyperlink.href = "#Edit";
    hyperlink.innerHTML = "Edit";
    hyperlink.setAttribute("onclick", "EditPolyline(this)");
    hyperlink.id = "hl" + cb.id;*/
    PolylineDiv.appendChild(cb);
    PolylineDiv.appendChild(label)
    //PolylineDiv.appendChild(hyperlink);
    divPolyline.appendChild(PolylineDiv);
}

function AddRemovePolyline(cb) {
    //    var btnPolyline = document.getElementById('btnPolyline');
    //    if (btnPolyline.value != "Start Track")
    //        EnablePolyline(btnPolyline);

    var idx = parseInt(cb.id.replace('cbp', ''));

    var Polyline = arrPolyline[idx - 1];
    if (cb.checked) {
        document.map.addOverlay(Polyline);
        showTrackInfo(idx);
    }
    else {
        document.map.removeOverlay(Polyline);
    }
}

function EditPolyline(hl) {
    /*var idx = parseInt(hl.id.replace('hlcbp', ''));
    var polyline = arrPolyline[idx - 1];
    if (hl.innerHTML == "Edit") {
    hl.innerHTML = "End Editing";
    polyline.enableEditing();
    }
    else {
    hl.innerHTML = "Edit";
    polyline.disableEditing();
    }*/
}

function DrawPolyLine(line) {
    var polyline = null;
    var split = line.split(comma);
    if (split.length % 2 == 1) {
        var LineName = split[0];
        var LocStart = new GLatLng(split[1], split[2]);
        var Loc2 = new GLatLng(split[3], split[4]);
        polyline = new GPolyline([LocStart, Loc2], "#ff0000", 3);

        var vertCount = 2;
        for (var j = 5; j < split.length; j += 2) {
            point = new GLatLng(split[j], split[j + 1]);
            polyline.insertVertex(vertCount, point);
            vertCount += 1;
        }


        document.map.addOverlay(polyline);
        polyline.enableEditing();
        PushPolyLine(polyline, LineName);
        EndPolyline(false);
    }
}

function SaveLines() {
    hfLines.value = "";
    for (var i = 0; i < arrPolyline.length; i++) {
        hfLines.value += arrPolylineName[i] + comma;
        var polyline = arrPolyline[i];
        for (var j = 0; j < polyline.getVertexCount(); j++) {
            var latlng = polyline.getVertex(j);
            hfLines.value += latlng.lat() + comma + latlng.lng();
            if (j != polyline.getVertexCount() - 1)
                hfLines.value += comma;
            else
                hfLines.value += semicolon;
        }
    }

}

function LoadLines() {

    if (hfLines.value != "") {
        var lines = hfLines.value.split(semicolon);
        for (var i = 0; i < lines.length - 1; i++) {
            DrawPolyLine(lines[i]);
        }
    }
}

///////////////////////////////////////////
///////////////////////////////////////////
///////////////////////////////////////////
///////////////////////////////////////////
//              ????????????????
///////////////////////////////////////////
///////////////////////////////////////////
///////////////////////////////////////////
///////////////////////////////////////////


function Reset() {
    isMarker = false;
    isPolyline = false;
}



function Draw(Location) {
    //if (isMarker)
    placeMarker(Location, "", "");
    //else if (isPolyline) {
    //first Click
    if (isLineStarted == false) {
        isLineStarted = true;
        LineLocStart = Location;
        document.getElementById("ctl00_ContentPlaceHolder1_GMap1_hfSavepoint").value = LineLocStart;
        getAddress(LineLocStart);
    }
    else if (isLineStarted == true) {
        AddToPolyline(Location, "");
    }

    //}
    //    else {
    //        isLineStarted = false;
    //        isLineEnded = false;
    //    }
}


///////////////////////////////////////////
///////////////////////////////////////////
///////////////////////////////////////////
///////////////////////////////////////////
//              WAYPOINTS
///////////////////////////////////////////
///////////////////////////////////////////
///////////////////////////////////////////
///////////////////////////////////////////

/*************Waypoint Class**************/
function Waipoint(wpId, wpName, wpDesc, wpPic, wpOrder) {
    this.wpId = wpId;
    this.wpName = wpName;
    this.wpDesc = wpDesc;
    this.wpPic = wpPic;
    this.wpOrder = wpOrder;
}

function showWaypointInfo(idx, isText) 
{
    UnhighlightMarker();
    var marker = arrMarker[idx - 1];
    var markerName = arrMarkerName[idx - 1];
    var markerDesc = arrMarkerDesc[idx - 1];
    var Pic = document.getElementById("hfcbm" + idx).value;
    var PicHTML = "<a href=javascript:AddPhoto(" + idx + ");>Add Photo</a>";
    if (Pic.length != 0)
        PicHTML = "<a href=javascript:EditPhoto(" + idx + ",'" + Pic + "');>Edit Photo</a>";
    if (isText) {
        PicHTML = "";
    }
    html = "<div id='wp" + idx + "' style='text-align:left;'><b>waypoint name</b><br><table><tr><td><textarea id='txtWaypointName' >" + markerName + "</textarea></td><td valign='top'><input type='button' onclick='updateWaypointName(" + idx + ");' value='OK'></td></tr></table><b>waypoint description</b><table><tr><td><textarea id='txtWaypointDesc' >" + markerDesc + "</textarea></td></tr></table><br>" + PicHTML + "&nbsp;&nbsp;<a href=javascript:deleteWaypoint(" + idx + ");>Delete Waypoint</a></div>";
    marker.openInfoWindowHtml(html);
    /*currPicDiv = document.getElementById("'wp" + idx + "'");
    map_canvas.appendChild(currPicDiv);*/
}

function updateWaypointName(idx) 
{
    var txt = document.getElementById('txtWaypointName');
    arrMarkerName[idx - 1] = txt.value;
    var desc = document.getElementById('txtWaypointDesc');
    arrMarkerDesc[idx - 1] = desc.value;
    document.map.closeInfoWindow();
    var lbl = document.getElementById('lblcbm' + idx.toString());
    lbl.innerHTML = txt.value;
}

function deleteWaypoint(idx) 
{
    var isDelete = confirm('Are you sure to Delete this Waypoint?');
    if (isDelete) {
        var marker = arrMarker[idx - 1];
        document.map.removeOverlay(marker);
        var cbm = document.getElementById('divcbm' + idx.toString());
        divMarker.removeChild(cbm);
    }
}

///////////////////////////////////////////
///////////////////////////////////////////
///////////////////////////////////////////
///////////////////////////////////////////
//              TRACK = TRAILS ???
///////////////////////////////////////////
///////////////////////////////////////////
///////////////////////////////////////////
///////////////////////////////////////////

function showTrackInfo(idx) 
{
    try {
        var Polyline = arrPolyline[idx - 1];
        var PolylineName = arrPolylineName[idx - 1];

        var point = Polyline.getVertex(Polyline.getVertexCount() - 1); // Need more attention

        if (point) {
            html = "<input id='txtPolylineName' value='" + PolylineName + "'><input type=button onclick='updateTrackName(" + idx + ");' value='update'><br><br><a href=javascript:deleteTrack(" + idx + ");>Delete Track</a>";
            document.map.openInfoWindowHtml(point, html);
        }
    }
    catch (e) { }
}

function updateTrackName(idx) 
{
    var txt = document.getElementById('txtPolylineName');

    document.getElementById('ctl00_ContentPlaceHolder1_GMap1_hfTrailName').value = txt.value;

    if (arrPolylineName && arrPolylineName.length > idx)
        arrPolylineName[idx - 1] = txt.value;
    document.map.closeInfoWindow();
    var lbl = document.getElementById('lblcbp' + idx.toString());
    lbl.innerHTML = txt.value + "&nbsp;&nbsp;";
}

function trimTrack(idx) {

}

function deleteTrack(idx) 
{
    var Polyline = arrPolyline[idx - 1];
    document.map.removeOverlay(Polyline);
    var cbp = document.getElementById('divcbp' + idx.toString());
    divPolyline.removeChild(cbp);
    document.map.closeInfoWindow();
}

function endTrail() 
{
    //    if (document.getElementById('btnPolyline').value == "End Track") {
    //        alert("Please first click the button 'End Track'");
    //        return false;
    //     }
    SaveTrail();
}

/**************Save Trail*****************/
function SaveTrail() 
{
    //    var btnPolyline = document.getElementById("btnPolyline");
    //    if (btnPolyline.value == "") {
    //        EndPolyline(false);
    //        btnPolyline.value = "Start Track";
    //    }

    // To insert Start point on postback
    EnableMarker('Start');
    //    if (LineLocStart != null) {
    //        placeMarker(LineLocStart, "Start Point", "");
    //    }

    SaveMarkers();
    SaveLines();

    var latlng = document.map.getCenter();
    hfCenter.value = latlng.lat() + "," + latlng.lng();
    hfZoom.value = document.map.getZoom();

}

function LoadTrail() {
    LoadMarkers();
    LoadLines();
    AnimateMarkers();
    if (location.href.indexOf('UI/Trail.aspx?TrailID=') > 0) {
        var elem = document.getElementById('hlcbp1');
        EditPolyline(elem);
    }
}


///////////////////////////////////////////
///////////////////////////////////////////
///////////////////////////////////////////
///////////////////////////////////////////
//             PHOTOS=IMAGES???
///////////////////////////////////////////
///////////////////////////////////////////
///////////////////////////////////////////
///////////////////////////////////////////

function AddPhoto(idx) {
    var hfMarkerIdx = document.getElementById("ctl00_ContentPlaceHolder1_GMap1_hfMarkerIdx");
    hfMarkerIdx.value = idx;

    var imgPic = document.getElementById("ctl00_ContentPlaceHolder1_GMap1_imgPic");
    imgPic.src = "";
    btnDelete.style.display = "none";
    ShowPicDiv();
}

function EditPhoto(idx, Pic) {
    var hfMarkerIdx = document.getElementById("ctl00_ContentPlaceHolder1_GMap1_hfMarkerIdx");
    hfMarkerIdx.value = idx;
    var imgPic = document.getElementById("ctl00_ContentPlaceHolder1_GMap1_imgPic");
    imgPic.src = Pic;
    btnDelete.style.display = "";
    ShowPicDiv();
}

function ShowPicDiv() {
    var divMsg = document.getElementById('PicDiv');
    divMsg.style.display = 'block';
}

function highlightTrailInfo(point, idx) 
{
    UnhighlightTrailInfo();

    if (document.map.getBounds().contains(point)) {
        maxDim = 70;

        var px1 = document.map.fromLatLngToDivPixel(point);
        var px2 = document.map.fromLatLngToDivPixel((document.map.getBounds()).getSouthWest());
        var mapHeight = parseInt(map_canvas.style.height.replace('px', ''));
        var px = new GPoint(px1.x - px2.x, px1.y - px2.y + mapHeight);

        currTrailDescDiv = document.createElement('div');
        currTrailDescDiv.style.position = 'absolute';
        currTrailDescDiv.style.top = px.y + 2 + 'px';
        currTrailDescDiv.style.left = px.x + 2 + 'px';
        currTrailDescDiv.style.zindex = 100;
        currTrailDescDiv.style.border = "1px solid #000000";
        currTrailDescDiv.closeIt = setTimeout(UnhighlightTrailInfo, 2000);
        currTrailDescDiv.onmouseover = function() { clearTimeout(currTrailDescDiv.closeIt); };
        currTrailDescDiv.onmouseout = function() { clearTimeout(currTrailDescDiv.closeIt); currTrailDescDiv.closeIt = setTimeout('UnhighlightTrailInfo()', 500); };
        var PicsHTML = "<table width='100%'><tr>";
        var trails = hfTrails.value.split(semicolon);
        var trail = trails[idx - 1];
        var split = trail.split(comma);

        for (var i = 5; i < split.length; i++) {
            PicsHTML += "<td><img src='../Upload/Trail/" + split[i] + "' style='width:" + maxDim + "px; height:" + maxDim + "px;'  /></td>";
        }
        PicsHTML += "</tr></table>";

        currTrailDescDiv.innerHTML = '<div style="text-align:left;border: 2px solid #FFFFFF;display:block; background-color:#fff; "><table><tr><td class="labelstyleBold"><a class="links" href="../UI/Trail-Details.aspx?TrailID=' + split[0] + '">' + split[1] + '</a> | ' + split[2] + '</td><td valign="top" rowspan="4" class="normal_font"><a href="javascript:UnhighlightTrailInfo();">X</a></td></tr><tr><td  class="labelstyleBold">length: 4.5 Km</td></tr><tr><td  class="labelstyleBold">Added by: <a class="links" href="../ui/userDetail.aspx?uid=' + split[3] + '">' + split[4] + '</a></td></tr><tr><td>' + PicsHTML + '</td></tr></table></div>';

        map_canvas.appendChild(currTrailDescDiv);
    }
}

function UnhighlightTrailInfo() {
    if (currTrailDescDiv) { map_canvas.removeChild(currTrailDescDiv); currTrailDescDiv = null; }
}

function AnimateMarkers() {
    if (hfMainImageID.value != "") {
        IntervalID = setInterval(HighlighNext, 5000);
    }
}

function HighlighNext() {
    var newIdx = GetNextPic(prevIdx + 1);
    if (newIdx == -1) {

        clearInterval(IntervalID);
        return;
    }
    var marker = arrMarker[newIdx];
    var icon = marker.getIcon();
    var img = icon.image.replace('.png', '_h.png');
    marker.setImage(img);
    ShowImage(newIdx);
    if (prevIdx != -1) {
        var marker = arrMarker[prevIdx];
        var icon = marker.getIcon();
        var img = icon.image.replace('_h.png', '.png');
        marker.setImage(img);
    }
    prevIdx = newIdx;
}

function GetNextPic(idx) 
{
    var i = idx;
    var hfPic = null;
    for (i = idx; i < arrMarker.length; i++) {
        var id = "hfcbm" + (i + 1);
        hfPic = document.getElementById(id);

        if (hfPic != null && hfPic.value != "")
            break;
        hfPic = null;
    }
    if (hfPic == null) {
        for (i = 0; i < idx; i++) {
            var id = "hfcbm" + (i + 1);
            hfPic = document.getElementById(id);
            if (hfPic != null && hfPic.value != "")
                break;
            hfPic = null;
        }
    }
    if (hfPic == null) {
        return -1;
    }
    return i;
}

function ShowImage(idx) 
{
    if (hfMainImageID.value != "") {
        var img = document.getElementById('imgTrail' + idx);
        if (img != null) {
            var imgMain = document.getElementById(hfMainImageID.value);
            if (imgMain != null) {
                imgMain.src = img.src;
            }
        }

    }
}


///////////////////////////////////////////
///////////////////////////////////////////
///////////////////////////////////////////
///////////////////////////////////////////
//            ADDRESS = reverse geocoding
///////////////////////////////////////////
///////////////////////////////////////////
///////////////////////////////////////////
///////////////////////////////////////////

function getAddress(latlng) 
{
    if (latlng != null) {
        address = latlng;
        geocoder.getLocations(latlng, showAddress);
    }
}

function showAddress(response) 
{
    if (response && response.Status.code == 200) {
        place = response.Placemark[0];
        hfCountry.value = place.AddressDetails.Country.CountryName + "," +
            place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName + "," +
            place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.SubAdministrativeAreaName;
    }
}
